package com.shigu.phoneCode.service;

import com.opentae.data.mall.beans.ValidCode;
import com.opentae.data.mall.examples.ValidCodeExample;
import com.opentae.data.mall.interfaces.ValidCodeMapper;
import com.shigu.exceptions.WapException;
import com.shigu.paypwd.util.RandomUtil;
import com.shigu.paypwd.util.SendMsgUtil;
import com.shigu.phoneCode.enums.PhoneCodeType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class PhoneCodeService {
    @Autowired
    ValidCodeMapper validCodeMapper;
    @Autowired
    SendMsgUtil sendMsgUtil;
    /**
     * 检查手机验证码是否正确
     * @param telephone
     * @param code
     * @param type
     * @return
     */
    public boolean checkPhoneCode(String telephone, String code, PhoneCodeType type, long timeout) throws WapException {
        ValidCodeExample example=new ValidCodeExample();
        example.createCriteria().andPhoneEqualTo(telephone).andCodeTypeEqualTo(type.getValue()).andCodeEqualTo(code);
        example.setStartIndex(0);
        example.setEndIndex(1);
        List<ValidCode> codes=validCodeMapper.selectByConditionList(example);
        validCodeMapper.deleteByExample(example);
        if (codes.size()==0) {
            throw new WapException("验证码不正确");
        }
        ValidCode c=codes.get(0);
        if (new Date().getTime()-c.getCodeTime().getTime()>timeout) {
            throw new WapException("验证码已过期");
        }
        return c.getCode().equals(code);
    }

    /**
     * @description 发送验证码
     * @param type 验证码类型 PhoneCodeType枚举类
     * @author 郭尔
     * @date 2019/2/18 16:39
     */
    @Cacheable(value = "valid_code_catch", key = "#telephone + '_' + #type")
    public  void sendCode(String telephone, Integer type){
        ValidCodeExample example = new ValidCodeExample();
        example.createCriteria().andPhoneEqualTo(telephone);
        validCodeMapper.deleteByExample(example);

        String random = RandomUtil.getRandom(6);
        sendMsgUtil.sendValiMsg(telephone, random);
        //插入表中
        ValidCode code = new ValidCode();
        code.setPhone(telephone);
        code.setCodeType(type);
        code.setCode(random);
        code.setCodeTime(new Date());
        validCodeMapper.insertSelective(code);
    }

}
